﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework.Input;

namespace Samples
{
    public class KeyboardMapper
    {
        public delegate void KeyFunction();

        #region KeyPressMap

        class KeyPressMap
        {
            private bool down;
            public Keys Key { get; set; }
            public KeyFunction Function { get; set; }

            public bool Check(ref KeyboardState state)
            {
                bool pressed = false;
                if (state.IsKeyDown(Key))
                {
                    if (down == false)
                        pressed = true;
                    down = true;
                }
                else { down = false; pressed = false; }
                return pressed;
            }
        }

        #endregion

        #region KeyDownMap

        class KeyDownMap
        {
            public Keys Key { get; set; }
            public KeyFunction Function { get; set; }

            public bool Check(ref KeyboardState state)
            {
                return state.IsKeyDown(Key);
            }
        }

        #endregion

        List<KeyPressMap> pressMaps = null;
        List<KeyDownMap> downMaps = null;

        public KeyboardMapper()
        {
            pressMaps = new List<KeyPressMap>();
            downMaps = new List<KeyDownMap>();
        }

        public void MapKeyPress(Keys key, KeyFunction func)
        {
            pressMaps.Add(new KeyPressMap() { Key = key, Function = func });
        }
        public void UnMapKeyPress(Keys key)
        {
            int i = 0;
            for (; i < pressMaps.Count; i++)
            {
                if (pressMaps[i].Key == key)
                    break;
            }
            if (i < pressMaps.Count)
                pressMaps.RemoveAt(i);
        }

        public void MapKeyDown(Keys key, KeyFunction func)
        {
            downMaps.Add(new KeyDownMap() { Key = key, Function = func });
        }
        public void UnMapKeyDown(Keys key)
        {
            int i = 0;
            for (; i < downMaps.Count; i++)
            {
                if (downMaps[i].Key == key)
                    break;
            }
            if (i < downMaps.Count)
                pressMaps.RemoveAt(i);
        }

        public void Update(ref KeyboardState state)
        {
            foreach (KeyPressMap k in pressMaps)
            {
                if (k.Check(ref state))
                    k.Function();
            }
            foreach (KeyDownMap k in downMaps)
            {
                if (k.Check(ref state))
                    k.Function();
            }
        }

    }
}
